<template>
    <div>
        <div>
            <el-form ref="searchForm" :inline="true" :model="condition.search" label-suffix="" label-width="100px"
                     label-position="left" size="small">
                <el-row>
                    <el-col :span=6>
                        <el-form-item label="任务名字" prop="jobName">
                            <el-input v-model="condition.search.jobName"
                                      placeholder="任务名字"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="任务类型" prop="jobType">
                            <el-select v-model="condition.search.jobType"
                                       placeholder="任务类型">
                                <el-option label="表达式任务"
                                           value="CRON"></el-option>
                                <el-option label="简单任务"
                                           value="SIMPLE"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="任务类名" prop="className">
                            <el-input v-model="condition.search.className"
                                      placeholder="任务类名"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item>
                            <el-button type="primary" @click="getData">查询</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="showAddDialog">新增</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="reset">重置</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="exportExcel">导出</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="success" @click="metaData">调度信息</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <el-table
            size="small"
            id="mainTable"
            :data="tableData"
            header-cell-class-name="tableHeaderStyle"
            :row-class-name="tableRowClassName">
            <el-table-column label="序号" width="60">
                <template v-slot="scope">
                    <span>{{ (condition.page - 1) * condition.rows + scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column
                prop="jobName"
                label="任务名字">
            </el-table-column>
            <el-table-column
                prop="jobType"
                label="任务类型">
            </el-table-column>
            <el-table-column
                prop="groupName"
                label="任务组名">
            </el-table-column>
            <el-table-column
                prop="triggerType"
                :formatter="formatTriggerType"
                label="触发类型">
            </el-table-column>
            <el-table-column
                prop="triggerName"
                label="触发器名">
            </el-table-column>
            <el-table-column
                prop="cronExpression"
                width="120px"
                label="CRON表达式">
            </el-table-column>
            <el-table-column
                prop="description"
                label="描述信息">
            </el-table-column>
            <el-table-column
                prop="status"
                :formatter="formatStatus"
                label="状态">
            </el-table-column>
            <el-table-column
                prop="updateTime"
                label="更新时间">
            </el-table-column>
            <el-table-column
                label="操作"
                fixed="right"
                align="center"
                width="240px">
                <template v-slot="scope">
                    <div>
                        <el-button @click="onPause(scope.row)" type="text" size="small"
                                   v-if="scope.row.status == 'NORMAL'">暂停
                        </el-button>
                        <el-button @click="onStart(scope.row)" type="text" size="small"
                                   v-if="scope.row.status == 'PAUSED'">启动
                        </el-button>
                        <el-button @click="showUpdateDialog(scope.row)" type="text" size="small">编辑</el-button>
                        <el-button @click="onDelete(scope.row)" type="text" size="small">删除</el-button>
                        <el-button @click="onExecuteNow(scope.row)" type="text" size="small">执行一次</el-button>
                        <el-button @click="executeWithParams(scope.row)" type="text" size="small">带参数执行</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            background
            small
            :hide-on-single-page="true"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="condition.page"
            :page-sizes="[10, 20, 30, 40, 50, 100]"
            :page-size.sync="condition.rows"
            layout="sizes, prev, pager, next"
            :total.sync="condition.total">
        </el-pagination>
        <el-dialog :title=addOrUpdateDialogTitle width="30%" :visible.sync="addOrUpdateDialogVisible">
            <el-form :model="addOrUpdateForm" label-width="120px" size="small">
                <el-form-item label="选择任务">
                    <el-select v-model="addOrUpdateForm.job" :disabled="addOrUpdateDialogTitle == '编辑'"
                               placeholder="选择任务">
                        <el-option
                            v-for="item in jobOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="任务名字">
                    <el-input v-model="addOrUpdateForm.jobName" :disabled="addOrUpdateDialogTitle == '编辑'"
                              placeholder="任务名字"></el-input>
                </el-form-item>
                <el-form-item label="触发类型">
                    <el-select v-model="addOrUpdateForm.triggerType"
                               placeholder="触发类型">
                        <el-option label="定时触发"
                                   value="CRON"></el-option>
                        <el-option label="简单触发"
                                   value="SIMPLE"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="触发器名">
                    <el-input v-model="addOrUpdateForm.triggerName"
                              placeholder="触发器名"></el-input>
                </el-form-item>
                <el-form-item label="CRON表达式">
                    <el-input v-model="addOrUpdateForm.cronExpression"
                              placeholder="CRON表达式"></el-input>
                    <div>
                        <el-link href="http://cron.ciding.cc/" target="_blank" type="warning">请点击这里查看如何配置
                        </el-link>
                    </div>
                </el-form-item>
                <el-form-item label="描述信息">
                    <el-input v-model="addOrUpdateForm.description" type="textarea"
                              placeholder="描述信息"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addOrUpdateDialogVisible = false" size="small">取 消</el-button>
                <el-button @click="addOrUpdateConfirm" type="primary" size="small">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="带参数执行" width="30%" :visible.sync="paramsDialogVisible">
            <el-form :model="paramsForm" label-width="120px" size="small">
                <el-form-item label="请输入参数">
                    <el-input v-model="paramsForm.paramsContent" type="textarea"
                              placeholder="请输入参数"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="paramsDialogVisible = false" size="small">取 消</el-button>
                <el-button @click="executeWithParamsConfirm" type="primary" size="small">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="调度信息" :visible.sync="schedulerDialogVisible" width="65%">
            <div><span style="white-space: pre-line">{{ schedulerMetaData.summary }}</span></div>
            <el-table size="mini" :data="schedulerInnerJobs" header-cell-class-name="tableHeaderStyle">
                <el-table-column prop="jobName" label="任务名字"></el-table-column>
                <el-table-column prop="groupName" label="任务组名"></el-table-column>
                <el-table-column prop="description" label="描述信息"></el-table-column>
                <el-table-column prop="triggerName" label="触发器名"></el-table-column>
                <el-table-column prop="triggerGroupName" label="触发器组名"></el-table-column>
                <el-table-column prop="triggerState" label="状态"></el-table-column>
                <el-table-column prop="nextFireTime" label="下次执行时间"></el-table-column>
                <el-table-column prop="cronExpression" width="120px" label="CRON表达式"></el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button @click="schedulerDialogVisible = false" type="success" size="small">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    addScheduleJob,
    deleteScheduleJob,
    executeNowScheduleJob,
    executeWithParamsScheduleJob,
    getOptions,
    getScheduleInnerJobs,
    getScheduleJobByPage,
    pauseScheduleJob,
    scheduleMetaData,
    startScheduleJob,
    updateScheduleJob
} from '@/api/api'

export default {
    name: "ScheduleJob",
    data() {
        return {
            // 分页搜索条件
            condition: {
                page: 1,
                rows: 10,
                total: 0,
                search: {}
            },
            // 表格数据
            tableData: [],
            // 新增或者编辑对话框显示
            addOrUpdateDialogVisible: false,
            // 标题
            addOrUpdateDialogTitle: '新增',
            // 新增或者编辑对话框表单
            addOrUpdateForm: {},
            // 选中行
            selectedRow: {},
            // job选项
            jobOptions: [],

            schedulerDialogVisible: false,
            schedulerMetaData: {},
            schedulerInnerJobs: [],

            paramsForm: {
                id: 0,
                paramsContent: '',
            },
            paramsDialogVisible: false,
        }
    },
    methods: {
        executeWithParams(row) {
            if (!row.paramsFlag) {
                this.$message({
                    type: 'error',
                    message: '该定时任务不支持带参数执行!'
                });
                return;
            }
            this.paramsForm.id = row.id;
            this.paramsForm.paramsContent = row.paramsContent;
            this.paramsDialogVisible = true;
        },
        executeWithParamsConfirm() {
            let oo = JSON.parse(this.paramsForm.paramsContent);
            executeWithParamsScheduleJob(this.paramsForm, oo).then(data => {
                if (data.respCode == 1000) {
                    this.paramsDialogVisible = false;
                }
            })
        },
        // 这里可以单独设置每一行的样式
        tableRowClassName({row, rowIndex}) {
            return '';
        },
        handleSizeChange(val) {
            this.getData();
        },
        handleCurrentChange(val) {
            this.getData();
        },
        // 格式布尔值
        formatBoolean: function (row, column, cellValue) {
            if (cellValue) {
                return "是";
            } else {
                return "否";
            }
        },
        formatTriggerType: function (row, column, cellValue) {
            if (cellValue == 'CRON') {
                return "定时触发";
            } else if (cellValue == 'SIMPLE') {
                return "简单触发";
            } else {
                return "未知";
            }
        },
        formatStatus: function (row, column, cellValue) {
            if (cellValue == 'PAUSED') {
                return "暂停";
            } else if (cellValue == 'NORMAL') {
                return "正常";
            } else {
                return "未知";
            }
        },
        showAddDialog: function () {
            this.addOrUpdateDialogTitle = '新增';
            this.addOrUpdateDialogVisible = true;
            this.addOrUpdateForm = {};
        },
        showUpdateDialog: function (row) {
            this.addOrUpdateDialogTitle = '编辑';
            this.addOrUpdateDialogVisible = true;
            this.selectedRow = row;
            // 深拷贝
            this.addOrUpdateForm = Object.assign({}, row);
            this.addOrUpdateForm.job = this.addOrUpdateForm.jobType;
        },
        reset: function () {
            this.$refs['searchForm'].resetFields();
        },
        exportExcel: function () {
            this.GLOBAL.exportExcel('#mainTable', '数据.xlsx');
        },
        add: function () {
            addScheduleJob(this.addOrUpdateForm).then(data => {
                if (data.respCode == 1000) {
                    this.addOrUpdateDialogVisible = false;
                    this.getData();
                }
            });
        },
        update: function () {
            updateScheduleJob(this.addOrUpdateForm).then(data => {
                if (data.respCode == 1000) {
                    this.addOrUpdateDialogVisible = false;
                    this.getData();
                }
            });
        },
        metaData: function () {
            scheduleMetaData().then(data => {
                if (data.respCode == 1000) {
                    this.schedulerDialogVisible = true;
                    this.schedulerMetaData = data.body;
                }
            })
            getScheduleInnerJobs().then(data => {
                if (data.respCode == 1000) {
                    this.schedulerInnerJobs = data.body;
                }
            })
        },
        onPause: function (row) {
            this.$confirm('请确认是否暂停, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                pauseScheduleJob({id: row.id}).then(data => {
                    if (data.respCode == 1000) {
                        this.$message({
                            type: 'success',
                            message: '暂停成功!'
                        });
                        this.getData();
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        onStart: function (row) {
            this.$confirm('请确认是否启动, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                startScheduleJob({id: row.id}).then(data => {
                    if (data.respCode == 1000) {
                        this.$message({
                            type: 'success',
                            message: '启动成功!'
                        });
                        this.getData();
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        onExecuteNow: function (row) {
            this.$confirm('请确认是否立即执行, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                executeNowScheduleJob({id: row.id}).then(data => {
                    if (data.respCode == 1000) {
                        this.$message({
                            type: 'success',
                            message: '执行成功!'
                        });
                        this.getData();
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        onDelete: function (row) {
            this.$confirm('请确认是否删除, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteScheduleJob({id: row.id}).then(data => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getData();
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        addOrUpdateConfirm: function () {
            if (this.addOrUpdateDialogTitle == '新增') {
                this.add();
            } else if (this.addOrUpdateDialogTitle == '编辑') {
                this.update();
            }
        },
        // 获取表格数据
        getData: function () {
            getScheduleJobByPage(this.condition).then(data => {
                this.tableData = data.body.rows;
                this.condition.total = data.body.total;
            });
            getOptions("ScheduleJob").then(data => {
                this.jobOptions = data.body;
            })
        },
    },
    created() {
        this.getData();
    },
}
</script>

<style scoped>
.el-input {
    width: 150px !important;
}

.el-select {
    width: 150px !important;
}
</style>
